package com.iptv.grape.load_apk;

import com.iptv.grape.util.AppLog;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class LoadApk {
    public static LoadApk loadApk;
    public static LoadApk ISTC(){
        if(null ==loadApk) {
            synchronized (LoadApk.class){
                loadApk = new LoadApk();
            }
        }
        return  loadApk;
    }

    public OkHttpClient okHttpClient;
    public Call  mCall;

    /***
     * 断点续传
     * @param url
     * @param fileName
     * @param tag
     * @param loadListener
     */
    public void download(String url,final String fileName,String tag, final LoadListener loadListener){
        final long startsPoint = getFileSize(fileName);
        AppLog.getCurLog().e("download====>1");
        Request request = new Request.Builder()
                .url(url)
                .header("RANGE", "bytes=" + startsPoint + "-")//断点续传
                .tag(tag)
                .build();

        // 重写ResponseBody监听请求
        Interceptor interceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder()
                        .body(new LoadResponseBody(originalResponse, startsPoint, loadListener))
                        .build();
            }
        };
        AppLog.getCurLog().e("download====>2");
        okHttpClient = new OkHttpClient.Builder()
                .addNetworkInterceptor(interceptor).build();

        // 发起请求
        mCall = okHttpClient.newCall(request);
        mCall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                loadListener.fail(e.hashCode(),e.getMessage());
                AppLog.getCurLog().e("download====>3");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                long length = response.body().contentLength();
                AppLog.getCurLog().e("download====>4");
                if (length == 0){
                    // 说明文件已经下载完，直接跳转安装就好
                    loadListener.complete(String.valueOf(createFile(fileName).getAbsoluteFile()));
                    return;
                }
                AppLog.getCurLog().e("download====>5");
                loadListener.start(length+startsPoint);
                // 保存文件到本地
                InputStream is = null;
                RandomAccessFile randomAccessFile = null;
                BufferedInputStream bis = null;

                byte[] buff = new byte[2048];
                int len = 0;
                try {
                    is = response.body().byteStream();
                    bis  =new BufferedInputStream(is);

                    File file = createFile(fileName);
                    // 随机访问文件，可以指定断点续传的起始位置
                    randomAccessFile =  new RandomAccessFile(file, "rwd");
                    randomAccessFile.seek (startsPoint);
                    while ((len = bis.read(buff)) != -1) {
                        randomAccessFile.write(buff, 0, len);
                    }
                    AppLog.getCurLog().e("download====>6");
                    // 下载完成
                    loadListener.complete(String.valueOf(file.getAbsoluteFile()));
                } catch (Exception e) {
                    AppLog.getCurLog().e("download====>6666");
                    e.printStackTrace();
                    loadListener.loadfail(e.getMessage());
                } finally {
                    AppLog.getCurLog().e("download====>7");
                    try {
                        if (is != null) {
                            is.close();
                        }
                        if (bis != null){
                            bis.close();
                        }
                        if (randomAccessFile != null) {
                            randomAccessFile.close();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
        });

    }


    /*****
     * 下载
     * @param url
     * @param fileName
     * @param tag
     * @param loadListener
     */
    public void download2(String url,final String fileName,String tag, final LoadListener loadListener){
        del(fileName);
        Request request = new Request.Builder()
                .url(url)
                .tag(tag)
                .build();
         File file = createFile(fileName);
        if(file==null){
            loadListener.loadfail("目录没有写入权限");
            return;
        }
        // 重写ResponseBody监听请求
        Interceptor interceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder()
                        .body(new LoadResponseBody(originalResponse, -1, loadListener))
                        .build();
            }
        };
        okHttpClient = new OkHttpClient.Builder()
                .addNetworkInterceptor(interceptor).build();

        // 发起请求
        mCall = okHttpClient.newCall(request);
        mCall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                loadListener.fail(e.hashCode(),e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                long length = response.body().contentLength();
                loadListener.start(length);
                InputStream is = null;
                byte[] buff = new byte[2048];
                int len;
                FileOutputStream fos = null;
                try {
                    is = response.body().byteStream();
                    File file = createFile(fileName);
                    fos = new FileOutputStream(file);
                    while ((len = is.read(buff)) != -1) {
                        fos.write(buff,0,len);
                    }
                    fos.flush();
                    // 下载完成
                    loadListener.complete(String.valueOf(file.getAbsoluteFile()));
                } catch (Exception e) {
                    del(fileName);
                    loadListener.loadfail(e.getMessage());
                } finally {
                    try {
                        if (is != null) {
                            is.close();
                        }
                        if (fos != null){
                            fos.close();
                        }
                    } catch (Exception e) {
                        loadListener.loadfail(e.getMessage());
                    }
                }

            }
        });

    }
    public void cancel(String tag){
        if(okHttpClient==null){
            return;
        }
        if(mCall==null)
            for (Call call : okHttpClient.dispatcher().runningCalls()) {
                if (call.request().tag().toString().contains(tag.toString())) {
                    call.cancel();
                }
            }
        else{
            mCall.cancel();
        }
    }
    private  File createFile(String fileName) {
        return  getFile(fileName);
    }

    public  long getFileSize(String fileName){
            File file = getFile(fileName);
            if(null == file){
                return 0;
            }
            return file.length();

    }

    public void delFile(String fileName){
        File file = new File(fileName);
        if(file.exists()){
            file.delete();
        }
    }
    public void del(String fileName){
        String root = "/sdcard/";
        File filePath = new File(root);
        if (!filePath.exists()||!filePath.isDirectory())
            return;
        File file = new File(root,fileName+".apk");
        if(file.exists()){
            file.delete();
        }
    }

    private File getFile(String fileName){
        try {
            String root = "/sdcard/";
            File filePath = new File(root);
            if (!filePath.exists()||!filePath.isDirectory())
                filePath.mkdirs();
            //修改权限
            File file = new File(root,fileName+".apk");
            if(!file.exists()||!file.isFile()) {
              file.createNewFile();
            }
            return file;
        } catch (IOException e) {
        }
        return null;
    }

}
